package com.cchip.cloud;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.TabActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;

import com.cchip.cloud.api.RsApi;
import com.cchip.cloud.system.Account;
import com.cchip.cloud.system.Config;

public class MainActivity extends TabActivity {

	private static final String TAG_ROOM = "tag.room";
	private static final String TAG_HISTORY = "tag.history";

	private static final int MENU_SETTING_ID = 1;
	private static final int MENU_LOGOUT_ID = 2;

	private Activity context = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		context = this;

		RsApi.getInstance().init();

		TabHost tabHost = getTabHost();

		TabSpec roomSpec = tabHost
				.newTabSpec(TAG_ROOM)
				.setIndicator("会议室",
						getResources().getDrawable(R.drawable.room))
				.setContent(new Intent(this, RoomActivity.class));
		TabSpec historySpec = tabHost
				.newTabSpec(TAG_HISTORY)
				.setIndicator("历史记录",
						getResources().getDrawable(R.drawable.history))
				.setContent(new Intent(this, HistoryActivity.class));

		tabHost.addTab(roomSpec);
		tabHost.addTab(historySpec);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		RsApi.getInstance().destroy();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, MENU_SETTING_ID, 0, "设置").setIcon(R.drawable.setting);
		menu.add(0, MENU_LOGOUT_ID, 1, "注销").setIcon(R.drawable.logout);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);
		int id = item.getItemId();

		switch (id) {
		case MENU_SETTING_ID:
			Intent setting = new Intent(this, SettingActivity.class);
			startActivity(setting);
			break;
		case MENU_LOGOUT_ID:
			showLogoutDialog();
			break;
		}

		return true;
	}

	private void showLogoutDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("注销");
		builder.setMessage("确认注销当前帐户(" + Account.my.name + ")?");
		builder.setNegativeButton("取消", null);
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				Account.my.clear();
				Config.setSavedAccount(false);
				Config.setAutoLogin(false);

				context.finish();

				Intent login = new Intent(context, LoginActivity.class);
				context.startActivity(login);
			}
		});
		builder.show();

	}
}
